package paper;

import java.util.*;
import java.util.regex.*;
import java.io.*;

public class RegExpVoter {

    Hashtable<String,Integer> candidates = new Hashtable<String,Integer>();
    
    public RegExpVoter() {
    }

    public void castVote(String x) {
        String xNew = "";
        for (int index=0; index<x.length(); index++) {
            char c = x.charAt(index);
            if ("()[]{}+*.".indexOf(c) != -1) {
                xNew += "\\" + c;
            } else {
                xNew += c;
            }
        }
        xNew = xNew.replaceAll("(,|\\\\\\.)","[\\\\.,]"); // !!!!!
        String x0 = xNew.replaceAll("\\p{Alpha}+","\\\\p{Alpha}+");
        String x1 = xNew.replaceAll("\\p{Digit}+","\\\\p{Digit}+\\\\p{Alpha}?");
        String x2 = x0.replaceAll("\\p{Digit}+","\\\\p{Digit}+\\\\p{Alpha}?");
        doVote(x2,15);
        doVote(x1,18);
        doVote(x0,18);
        doVote(xNew,20);
    }

    public void doVote(String x, int n) {
        Integer i = candidates.get(x);
        if (i == null) {
            i = new Integer(0);
        }
        candidates.put(x, i+n);
    }


    public Pattern winningPattern() {
        Enumeration<String> i = candidates.keys();
        int biggest = 0;
        String bestTag = "";
        while (i.hasMoreElements()) {
            String tag = i.nextElement();
            int num = candidates.get(tag);
//            System.out.println("? "+ tag + " " + num);
            if (num > biggest) {
                bestTag = tag;
                biggest = num;
            }
        }
//        System.out.println("= "+ bestTag);
        return Pattern.compile(bestTag);
    }

}
